# -*- coding: utf-8 -*-
from kafka import KafkaProducer
from imutils.video import VideoStream
import requests
import imutils
import numpy as np
import time
import cv2
from PIL import Image
from io import BytesIO
import base64
import json,io
import struct
import avro.schema
from avro.io import DatumWriter, BinaryEncoder


# 参考 https://www.cnpython.com/qa/279146
def publish_video(server, topic, rtsp, api_url):
   schema = avro.schema.parse(open("avro/init_kafka_key.avsc", "rb").read())

   producer = KafkaProducer(bootstrap_servers=server)
   vs = VideoStream(src=rtsp).start()
   time.sleep(2.0)

   print("publishing video...")

   while True:
      frame = vs.read()
      #frame = process(frame, api_url)
#       frame = imutils.resize(frame, width=700)
      frame = imutils.resize(frame, width=400)
      #frame = imutils.resize(frame, width=1080)
      #frame = imutils.resize(frame)
      # send to kafka topic
      #producer.send(topic, key=struct.pack('<f', time.time()) ,value=frame.tobytes())

      #datum_writer = DatumWriter(schema)
      #byte_writer = io.BytesIO()
      #datum_encoder = BinaryEncoder(byte_writer)
      #datum_writer.write(kkey,datum_encoder)
      #producer.send(topic, key=byte_writer.getvalue() ,value=frame.tobytes())

      kkey = {"key": time.time() }
      print(kkey)
      producer.send(topic, key= bytes(str(time.time()),"utf8")  ,value=frame.tobytes())
   vs.stop()


#def process(frame, api_url):
#   img = Image.fromarray(frame)
#   output_buffer = BytesIO()  # 创建一个BytesIO
#   img.save(output_buffer, format='JPEG')  # 写入output_buffer
#   byte_data = output_buffer.getvalue()  # 在内存中读取
#   image_base64 = base64.b64encode(byte_data).decode()  # 转为BASE64
#   data = json.dumps(
#      {"image": image_base64, "visual_result": "True", "username": "xsrt", "password": "dGVzdC1wd2QxMjM="})
#   headers = {"Content-Type": "application/json"}
#   response = requests.post(api_url, data=data, headers=headers)
#   result = response.text
#   result = json.loads(result)
#   try:
#      base64_img = result["base64"]
#      process_img = base64.b64decode(base64_img)
#      img = cv2.imdecode(np.frombuffer(process_img, np.uint8), cv2.IMREAD_COLOR)
#      img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
#   except:
#      img = frame
#
#   return img


def process_list(result):
   for i in result:
      result_i = i
      result_i_bbox = result_i["bbox"]
      for i in range(len(result_i_bbox)):
         result_i_bbox[i] = result_i_bbox[i] * 2
   return result


if __name__ == '__main__':
   server = 'kafka:9092'
   topic = 'rtsp'
   # rtsp = 'rtsp://admin:a1234567@192.168.20.87:554/h264/ch1/main/av_stream'
   #rtsp = "rtsp://admin:nncsys2019@192.168.100.92"
   rtsp = "rtsp://admin:HikJMWWLW@192.168.1.64"
   api_url = 'http://192.168.1.64:8191/fire/json'
   publish_video(server, topic, rtsp, api_url)

